package com.hymane.materialhome.ui.activity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.protobuf.InvalidProtocolBufferException;
import com.hymane.materialhome.MaterialMessage;
import com.hymane.materialhome.R;
import com.hymane.materialhome.bean.http.douban.BookInfoResponse;
import com.hymane.materialhome.utils.Declare;
import com.hymane.materialhome.utils.HttpUtil;
import com.hymane.materialhome.utils.User;
import com.hymane.materialhome.utils.Utils;

public class LoginActivity extends Activity implements OnClickListener,
		OnItemClickListener, OnDismissListener {
	protected static final String TAG = "LoginActivity";
	private LinearLayout mLoginLinearLayout; // 登录内容的容器
	private LinearLayout mUserIdLinearLayout; // 将下拉弹出窗口在此容器下方显示
	private Animation mTranslate; // 位移动画
	private Dialog mLoginingDlg; // 显示正在登录的Dialog
	private EditText mIdEditText; // 登录ID编辑框
	private EditText mPwdEditText; // 登录密码编辑框
	private ImageView mMoreUser; // 下拉图标
	private Button mLoginButton; // 登录按钮
	private ImageView mLoginMoreUserView; // 弹出下拉弹出窗的按钮
	private String mIdString;
	private String mPwdString;
	private ArrayList<User> mUsers; // 用户列表
	private ListView mUserIdListView; // 下拉弹出窗显示的ListView对象
	private MyAapter mAdapter; // ListView的监听器
	private PopupWindow mPop; // 下拉弹出窗

    private Button mLoadBookListButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		initView();
		setListener();
		mLoginLinearLayout.startAnimation(mTranslate); // Y轴水平移动

		/* 获取已经保存好的用户密码 */
		mUsers = Utils.getUserList(LoginActivity.this);

		if (mUsers.size() > 0) {
			/* 将列表中的第一个user显示在编辑框 */
			mIdEditText.setText(mUsers.get(0).getId());
			mPwdEditText.setText(mUsers.get(0).getPwd());
		}

		LinearLayout parent = (LinearLayout) getLayoutInflater().inflate(
				R.layout.userifo_listview, null);
		mUserIdListView = (ListView) parent.findViewById(android.R.id.list);
		parent.removeView(mUserIdListView); // 必须脱离父子关系,不然会报错
		mUserIdListView.setOnItemClickListener(this); // 设置点击事
		mAdapter = new MyAapter(mUsers);
		mUserIdListView.setAdapter(mAdapter);

//        new Thread(runnable).start();

	}
    private class MyTask extends AsyncTask<String, Integer, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute() called");
//            textView.setText("loading...");
        }

        //doInBackground方法内部执行后台任务,不可在此方法内修改UI
        @Override
        protected String doInBackground(String... params) {
            Log.i(TAG, "doInBackground(Params... params) called");

            String url = null;
            try {
                url = HttpUtil.BASE_URL
                        + "LoginServlet?userName="
                        + URLEncoder.encode(
                        URLEncoder.encode(params[0], "UTF-8"), "UTF-8")+"&password="
                        + URLEncoder.encode(
                        URLEncoder.encode(params[1], "UTF-8"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // 查询返回结果
            String result = HttpUtil.queryStringForPost(url);
            return result;
//            try {
//                HttpClient client = new DefaultHttpClient();
//                HttpGet get = new HttpGet(params[0]);
//                HttpResponse response = client.execute(get);
//                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                    HttpEntity entity = response.getEntity();
//                    InputStream is = entity.getContent();
//                    long total = entity.getContentLength();
//                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                    byte[] buf = new byte[1024];
//                    int count = 0;
//                    int length = -1;
//                    while ((length = is.read(buf)) != -1) {
//                        baos.write(buf, 0, length);
//                        count += length;
//                        //调用publishProgress公布进度,最后onProgressUpdate方法将被执行
//                        publishProgress((int) ((count / (float) total) * 100));
//                        //为了演示进度,休眠500毫秒
//                        Thread.sleep(500);
//                    }
//                    return new String(baos.toByteArray(), "gb2312");
//                }
//            } catch (Exception e) {
//                Log.e(TAG, e.getMessage());
//            }
//            return null;
        }

        //onProgressUpdate方法用于更新进度信息
        @Override
        protected void onProgressUpdate(Integer... progresses) {
            Log.i(TAG, "onProgressUpdate(Progress... progresses) called");
//            progressBar.setProgress(progresses[0]);
//            textView.setText("loading..." + progresses[0] + "%");
        }

        //onPostExecute方法用于在执行完后台任务后更新UI,显示结果
        @Override
        protected void onPostExecute(String result) {
            Log.i(TAG, "onPostExecute(Result result) called");
            if(!result.equals("0")){
                int userId = Integer.parseInt(result);
                String userName = mIdEditText.getText().toString();

//                Declare declare = (Declare) getApplicationContext();
//                declare.setId(userId);
//                declare.setUserName(userName);

                Intent intent = new Intent(LoginActivity.this, MainActivity.class);

                //可以把要传递的参数放到一个bundle里传递过去，bundle可以看做一个特殊的map.
                Bundle bundle=new Bundle();
                bundle.putInt("id", userId);
                bundle.putString("name", userName);
                intent.putExtras(bundle);

                startActivity(intent);
                LoginActivity.this.finish();

                closeLoginingDlg();// 关闭对话框
                Toast.makeText(getApplicationContext(), "登入成功", Toast.LENGTH_SHORT).show();

            }else{
                Toast.makeText(getApplicationContext(), "登入失败", Toast.LENGTH_SHORT).show();
            }
        }

        //onCancelled方法用于在取消执行中的任务时更改UI
        @Override
        protected void onCancelled() {
            Log.i(TAG, "onCancelled() called");
//            textView.setText("cancelled");
//            progressBar.setProgress(0);
//
//            execute.setEnabled(true);
//            cancel.setEnabled(false);
        }
    }

	private class LoadBooklistTask extends AsyncTask<String, Integer, byte[]> {
		//onPreExecute方法用于在执行后台任务前做一些UI操作
		@Override
		protected void onPreExecute() {
			Log.i(TAG, "onPreExecute() called");
//            textView.setText("loading...");
		}

		//doInBackground方法内部执行后台任务,不可在此方法内修改UI
		@Override
		protected  byte[] doInBackground(String... params) {

			String url = HttpUtil.BASE_URL + "BookListServlet";
			byte _byte[] = HttpUtil.queryByteArrayForPost(url);
			return _byte;
//            try {
//                HttpClient client = new DefaultHttpClient();
//                HttpGet get = new HttpGet(params[0]);
//                HttpResponse response = client.execute(get);
//                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                    HttpEntity entity = response.getEntity();
//                    InputStream is = entity.getContent();
//                    long total = entity.getContentLength();
//                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                    byte[] buf = new byte[1024];
//                    int count = 0;
//                    int length = -1;
//                    while ((length = is.read(buf)) != -1) {
//                        baos.write(buf, 0, length);
//                        count += length;
//                        //调用publishProgress公布进度,最后onProgressUpdate方法将被执行
//                        publishProgress((int) ((count / (float) total) * 100));
//                        //为了演示进度,休眠500毫秒
//                        Thread.sleep(500);
//                    }
//                    return new String(baos.toByteArray(), "gb2312");
//                }
//            } catch (Exception e) {
//                Log.e(TAG, e.getMessage());
//            }
//            return null;
		}

		//onProgressUpdate方法用于更新进度信息
		@Override
		protected void onProgressUpdate(Integer... progresses) {
			Log.i(TAG, "onProgressUpdate(Progress... progresses) called");
//            progressBar.setProgress(progresses[0]);
//            textView.setText("loading..." + progresses[0] + "%");
		}

		//onPostExecute方法用于在执行完后台任务后更新UI,显示结果
		@Override
		protected void onPostExecute(byte[] result) {
			MaterialMessage.TransPackage transPackage = null;
			try {
				transPackage = MaterialMessage.TransPackage.parseFrom(result);
			} catch (InvalidProtocolBufferException e) {
				e.printStackTrace();
				return;
			}
			if (transPackage.getId() == MaterialMessage.TransPackage.PackageId.LoadBookList) {
				byte[] bytesBook = transPackage.getPackage().toByteArray();
				BookInfoResponse bookInfoResponse;
				//反序列化,将该对象恢复(存储到一个文件)
				try {
					ByteArrayInputStream byteArrayOutputStream = new ByteArrayInputStream(bytesBook);
					ObjectInputStream ois = new ObjectInputStream(byteArrayOutputStream);
					try {
						bookInfoResponse = (BookInfoResponse) ois.readObject();
						String strImage = bookInfoResponse.getImage();

					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		//onCancelled方法用于在取消执行中的任务时更改UI
		@Override
		protected void onCancelled() {
			Log.i(TAG, "onCancelled() called");
//            textView.setText("cancelled");
//            progressBar.setProgress(0);
//
//            execute.setEnabled(true);
//            cancel.setEnabled(false);
		}
	}

	/* ListView的适配器 */
	class MyAapter extends ArrayAdapter<User> {

		public MyAapter(ArrayList<User> users) {
			super(LoginActivity.this, 0, users);
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(
						R.layout.listview_item, null);
			}

			TextView userIdText = (TextView) convertView
					.findViewById(R.id.listview_userid);
			userIdText.setText(getItem(position).getId());

			ImageView deleteUser = (ImageView) convertView
					.findViewById(R.id.login_delete_user);
			deleteUser.setOnClickListener(new OnClickListener() {
				// 点击删除deleteUser时,在mUsers中删除选中的元素
				@Override
				public void onClick(View v) {

					if (getItem(position).getId().equals(mIdString)) {
						// 如果要删除的用户Id和Id编辑框当前值相等，则清空
						mIdString = "";
						mPwdString = "";
						mIdEditText.setText(mIdString);
						mPwdEditText.setText(mPwdString);
					}
					mUsers.remove(getItem(position));
					mAdapter.notifyDataSetChanged(); // 更新ListView
				}
			});
			return convertView;
		}

	}

	private void setListener() {
		mIdEditText.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				mIdString = s.toString();
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
			}
		});
		mPwdEditText.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				mPwdString = s.toString();
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
			}
		});
		mLoginButton.setOnClickListener(this);
		mLoginMoreUserView.setOnClickListener(this);

        mLoadBookListButton.setOnClickListener(this);
	}

	private void initView() {
		mIdEditText = (EditText) findViewById(R.id.login_edtId);
		mPwdEditText = (EditText) findViewById(R.id.login_edtPwd);
		mMoreUser = (ImageView) findViewById(R.id.login_more_user);
		mLoginButton = (Button) findViewById(R.id.login_btnLogin);
		mLoginMoreUserView = (ImageView) findViewById(R.id.login_more_user);
		mLoginLinearLayout = (LinearLayout) findViewById(R.id.login_linearLayout);
		mUserIdLinearLayout = (LinearLayout) findViewById(R.id.userId_LinearLayout);
		mTranslate = AnimationUtils.loadAnimation(this, R.anim.my_translate); // 初始化动画对象

        mLoadBookListButton = (Button)findViewById(R.id.btn_load_booklist);

		initLoginingDlg();
	}

	public void initPop() {
		int width = mUserIdLinearLayout.getWidth() - 4;
		int height = LayoutParams.WRAP_CONTENT;
		mPop = new PopupWindow(mUserIdListView, width, height, true);
		mPop.setOnDismissListener(this);// 设置弹出窗口消失时监听器

		// 注意要加这句代码，点击弹出窗口其它区域才会让窗口消失
		mPop.setBackgroundDrawable(new ColorDrawable(0xffffffff));

	}

	/* 初始化正在登录对话框 */
	private void initLoginingDlg() {

		mLoginingDlg = new Dialog(this, R.style.loginingDlg);
		mLoginingDlg.setContentView(R.layout.logining_dlg);

		Window window = mLoginingDlg.getWindow();
		WindowManager.LayoutParams params = window.getAttributes();
		// 获取和mLoginingDlg关联的当前窗口的属性，从而设置它在屏幕中显示的位置

		// 获取屏幕的高宽
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int cxScreen = dm.widthPixels;
		int cyScreen = dm.heightPixels;

		int height = (int) getResources().getDimension(
				R.dimen.loginingdlg_height);// 高42dp
		int lrMargin = (int) getResources().getDimension(
				R.dimen.loginingdlg_lr_margin); // 左右边沿10dp
		int topMargin = (int) getResources().getDimension(
				R.dimen.loginingdlg_top_margin); // 上沿20dp

		params.y = (-(cyScreen - height) / 2) + topMargin; // -199
		/* 对话框默认位置在屏幕中心,所以x,y表示此控件到"屏幕中心"的偏移量 */

		params.width = cxScreen;
		params.height = height;
		// width,height表示mLoginingDlg的实际大小

		mLoginingDlg.setCanceledOnTouchOutside(true); // 设置点击Dialog外部任意区域关闭Dialog
	}

	/* 显示正在登录对话框 */
	private void showLoginingDlg() {
		if (mLoginingDlg != null)
			mLoginingDlg.show();
	}

	/* 关闭正在登录对话框 */
	private void closeLoginingDlg() {
		if (mLoginingDlg != null && mLoginingDlg.isShowing())
			mLoginingDlg.dismiss();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_btnLogin:
			// 启动登录
			showLoginingDlg(); // 显示"正在登录"对话框,因为此Demo没有登录到web服务器,所以效果可能看不出.可以结合情况使用
			Log.i(TAG, mIdString + "  " + mPwdString);
			if (mIdString == null || mIdString.equals("")) { // 账号为空时
				Toast.makeText(LoginActivity.this, "请输入账号", Toast.LENGTH_SHORT)
						.show();
			} else if (mPwdString == null || mPwdString.equals("")) {// 密码为空时
				Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT)
						.show();
			} else {// 账号和密码都不为空时
				boolean mIsSave = true;
				try {
					Log.i(TAG, "保存用户列表");
					for (User user : mUsers) { // 判断本地文档是否有此ID用户
						if (user.getId().equals(mIdString)) {
							mIsSave = false;
							break;
						}
					}
					if (mIsSave) { // 将新用户加入users
						User user = new User(mIdString, mPwdString);
						mUsers.add(user);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
                //注意每次需new一个实例,新建的任务只能执行一次,否则会出现异常

                String[] params = {
                        mIdEditText.getText().toString(),
                        mPwdEditText.getText().toString()
                };

                new MyTask().execute(params);
//                handleLogon();
            }
			break;
		case R.id.login_more_user: // 当点击下拉栏
			if (mPop == null) {
				initPop();
			}
			if (!mPop.isShowing() && mUsers.size() > 0) {
				// Log.i(TAG, "切换为角向上图标");
				mMoreUser.setImageResource(R.drawable.login_more_down); // 切换图标
				mPop.showAsDropDown(mUserIdLinearLayout, 2, 1); // 显示弹出窗口
			}
			break;
		case R.id.btn_load_booklist:
			new LoadBooklistTask().execute(new String[0]);
			break;
		default:
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		mIdEditText.setText(mUsers.get(position).getId());
		mPwdEditText.setText(mUsers.get(position).getPwd());
		mPop.dismiss();
	}

	/* PopupWindow对象dismiss时的事件 */
	@Override
	public void onDismiss() {
		// Log.i(TAG, "切换为角向下图标");
		mMoreUser.setImageResource(R.drawable.login_more_up);
	}

	/* 退出此Activity时保存users */
	@Override
	public void onPause() {
		super.onPause();
		try {
			Utils.saveUserList(LoginActivity.this, mUsers);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void handleLogon(){
		try {
//            从Honeycomb SDK（3.0）开始，google不再允许网络请求（HTTP、Socket）等相关操作直接在Main Thread类中
			String url = HttpUtil.BASE_URL
					+ "LoginServlet?userName="
					+ URLEncoder.encode(
					URLEncoder.encode(mIdEditText.getText().toString(), "UTF-8"), "UTF-8")+"&password="
					+ URLEncoder.encode(
					URLEncoder.encode(mPwdEditText.getText().toString(), "UTF-8"), "UTF-8");
			// 查询返回结果
			String result = HttpUtil.queryStringForPost(url);
			if(!result.equals("0")){
                int userId = Integer.parseInt(result);
                String userName = mIdEditText.getText().toString();

				Declare declare = (Declare) getApplicationContext();
				declare.setId(userId);
				declare.setUserName(userName);

                Intent intent = new Intent(this, MainActivity.class);

                //可以把要传递的参数放到一个bundle里传递过去，bundle可以看做一个特殊的map.
                Bundle bundle=new Bundle();
                bundle.putInt("id", userId);
                bundle.putString("name", userName);
                intent.putExtras(bundle);

                startActivity(intent);
				LoginActivity.this.finish();

                closeLoginingDlg();// 关闭对话框
                Toast.makeText(getApplicationContext(), "登入成功", Toast.LENGTH_SHORT).show();

            }else{
				Toast.makeText(getApplicationContext(), "登入失败", Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.i("LoginActivity",e.toString());
		}
	}

//    Handler handler = new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            Bundle data = msg.getData();
//            String val = data.getString("value");
//            Log.i(TAG,"请求结果:" + val);
//        }
//    };
//
//    Runnable runnable = new Runnable(){
//        @Override
//        public void run() {
//            // TODO: http request.
//            Message msg = new Message();
//            Bundle data = new Bundle();
//            data.putString("value","请求结果");
//            msg.setData(data);
//            handler.sendMessage(msg);
//        }
//    };

}
